<template>

  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :modal-append-to-body="false">
    <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="20%"
             style='width: 90%; margin-left:1%;'>
      <el-form-item v-if="dialogStatus == 'create'" label="父级" prop="">
        <span class="fontShow2">{{temp.show}}</span>
      </el-form-item>
      <el-form-item label="备件名称" prop="partName">
        <el-input v-model="temp.partName"></el-input>
      </el-form-item>
      <el-form-item label="备件属性" prop="partSourceType">
        <el-radio-group v-model="temp.partSourceType" size="mini">
          <el-radio v-for="(value, key) in _PartSourceType" :key="key" :label="key">{{value}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备件类型" prop="partType">
        <el-radio-group v-model="temp.partType" size="mini">
          <el-radio v-for="(value, key) in _PartType" :key="key" :label="key">{{value}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="采购方式" prop="purchaseType">
        <el-radio-group v-model="temp.purchaseType" size="mini">
          <el-radio v-for="(value, key) in _PurchaseType" :key="key" :label="key">{{value}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="规格型号" prop="specType">
        <el-input v-model="temp.specType"></el-input>
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="temp.unit"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input :autosize="{ minRows: 1, maxRows: 3}" v-model="temp.remark" type="textarea" placeholder="备注"/>
      </el-form-item>
      <el-form-item v-for="(attr, i) in temp.attrList"
                    :label="'扩展属性' + i" :key="attr.key" :prop="'attrList.' + i + '.attrName'">
        <el-col :span="8">
          <el-input v-model="attr.attrName" placeholder="属性名"></el-input>
        </el-col>
        <el-col :span="8">
          <el-input v-model="attr.attrVal" placeholder="属性值"></el-input>
        </el-col>
        <el-col :span="6">
          &nbsp;&nbsp;<el-button @click.prevent="addAttr()" size="mini" type="success"><i class="el-icon-plus"></i>
        </el-button>
          <el-button @click.prevent="removeAttrs(attr)" size="mini" type="danger"><i class="el-icon-delete"></i>
          </el-button>
        </el-col>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button v-if="applyType" type="danger" @click="addSubmit(0)" id="cfmbtm5">保存</el-button>
      <el-button v-if="dialogStatus=='create'" type="primary" @click="addSubmit(1)" id="cfmbtm3">确 定</el-button>
      <el-button v-else type="primary" @click="updateSubmit" id="cfmbtm4">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>

  import {createOne, deleteOne, updateOne, updateOneNoId} from '@/api/common'
  import {disableBtn, df, $err, $suc, ERRS, SUCS} from '@/utils'
  import mixinCode from './mixinCode'

  export default {
    mixins: [mixinCode],
    name: 'deviceComp',
    props: {
      // levStatus: Number,
      treeNodeData: Object,
    },
    data: function () {
      return {
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {update: '编辑备件', create: '添加备件'},
        temp: {},
        applyType: 0,  //发起方式 0直接添加 1发起申请
        rules: {
          partName: [
            {required: true, message: '请输入备件名', trigger: 'blur'},
            {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
          ],

        }
      }
    },

    methods: {

      // + - 属性项
      removeAttrs(item) {
        var index = this.temp.attrList.indexOf(item)
        if (index !== -1) {
          this.temp.attrList.splice(index, 1)
        }
      },
      addAttr() {
        this.temp.attrList.push({attrName: '', attrVal: ''});
      },

      addDevice(type) {
        this.applyType = type
        const row = this.treeNodeData
        console.log(row);
        if (!row._id) {
          ERRS('请选择左侧编码层级!');
          return
        } else if (!(row.codeType === 'CODE_END')) {
          ERRS('只能选择编码结束节点添加备件!');
          return
        } else {

          let show = `${row.level + 1}级  ${row.explainText}  编码:${row.fullCodeNo}`
          this.temp = {
            codeEndId: row._id,
            iconUrl: "http://njchome.b0.upaiyun.com/hlsnzj/default_header.jpg?imageView2/1/w/80/h/80",
            partName: "",   //备件名称
            partSourceType: "PURCHASE", //备件属性 PURCHASE, RANDOM
            partType: "ORDINARY",       //备件类型 故障备件、一般备件 FAULT, ORDINARY
            purchaseType: "LING_CAI",       //“采购方式”包含：零采、统购、委托采购、寄售
            remark: "",
            specType: "",   // 规格型号
            unit: "",   // 单位
            attrList: [     // 属性
              {
                attrName: "",
                attrVal: "",
              }
            ],
            show: show
          };
          // this.$emit('update:tData', row)
          this.dialogStatus = 'create'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })

        }
      },

      addSubmit(type) {
        console.log(this.applyType)
        this.dialogFormVisible = false
        if (this.applyType) {
          //见api.md
          let tp=this.temp
          this.temp={
            opFormJson:JSON.stringify(tp),
            submit:type ? true : false  //提交?保存
          }
          this.doSubmit('/flowable/ru/code_flowable/start', 'cfmbtm5')

        } else {
          delete this.temp.show
          this.doSubmit('sparepartscode/parts', 'cfmbtm3')
        }
      },
      doSubmit(url, btn) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn(btn);
            createOne(url, this.temp).then(res => {
              if (res.code === 0) {
                SUCS('添加成功!')
                this.$emit('childGetList')
              } else {
                ERRS(res.message)
              }
            })
          }
        })
      },
      updateDevice(row) {
        console.log(row);
        let exp = row.codeExplain;
        this.temp = {
          id: row._id,
          codeEndId: exp.parent._id,
          iconUrl: row.iconUrl,
          partName: row.partName,   //备件名称
          partSourceType: row.partSourceType, //备件属性 PURCHASE, RANDOM
          partType: row.partType,       //备件类型 故障备件、一般备件 FAULT, ORDINARY
          purchaseType: row.purchaseType,       //“采购方式”包含：零采、统购、委托采购、寄售
          remark: row.remark,
          specType: row.specType,   // 规格型号
          unit: row.unit,   // 单位
          attrList: row.partAttrList, //其它属性
        };
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })

      },
      updateSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm4');
            updateOne(`sparepartscode/parts`, this.temp).then(res => {
              this.dialogFormVisible = false
              if (res.code === 0) {
                SUCS('修改成功!')
                this.$emit('childGetList')
              } else {
                ERRS(res.data.message)
              }
            })
          }
        })
      },

    }
  }
</script>

